package com.realdolmen.whiteyellowcross.appengine.datastore;

import static com.google.appengine.api.datastore.FetchOptions.Builder.withLimit;

import java.util.Date;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.Filter;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.FilterPredicate;
import com.realdolmen.whiteyellowcross.datastore.WaitWorkShiftDataStore;
import com.realdolmen.whiteyellowcross.model.WaitWorkShift;

public class WaitWorkShiftAppEngineDataStore implements WaitWorkShiftDataStore {

	private DatastoreService datastoreService;

	public WaitWorkShiftAppEngineDataStore(DatastoreService datastoreService) {
		this.datastoreService = datastoreService;
	}

	public DatastoreService getDatastoreService() {
		return datastoreService;
	}

	@Override
	public void addWaitWorkShift(String name, Date from, Date to, Integer hours) {
		Entity waitWorkShift = new Entity(
				WaitWorkShift.class.getCanonicalName());
		waitWorkShift.setProperty("name", name);
		waitWorkShift.setProperty("from", from);
		waitWorkShift.setProperty("to", to);
		waitWorkShift.setProperty("hours", hours);
		datastoreService.put(waitWorkShift);
	}

	@Override
	public WaitWorkShift getWaitWorkShift(String name) {
		WaitWorkShift waitWorkShift = null;

		Entity entity = getWaitWorkShiftEntity(name);
		if (entity != null) {
			waitWorkShift = transFormEntityToWaitWorkShift(entity);
		}

		return waitWorkShift;
	}

	private Entity getWaitWorkShiftEntity(String name) {
		Query query = new Query(WaitWorkShift.class.getCanonicalName());
		Filter filter = new FilterPredicate("name", FilterOperator.EQUAL, name);
		query.setFilter(filter);
		PreparedQuery preparedQuery = datastoreService.prepare(query);
		Entity entity = preparedQuery.asSingleEntity();
		return entity;
	}

	@Override
	public void deleteWaitWorkShift(String name) {
		Entity entity = getWaitWorkShiftEntity(name);
		datastoreService.delete(entity.getKey());
	}

	@Override
	public int getTotalWaitWorkShifts() {
		Query query = new Query(WaitWorkShift.class.getCanonicalName());
		PreparedQuery preparedQuery = datastoreService.prepare(query);
		return preparedQuery.countEntities(withLimit(100));
	}

	private WaitWorkShift transFormEntityToWaitWorkShift(Entity entity) {
		WaitWorkShift waitWorkShift = null;
		if (entity != null) {
			waitWorkShift = new WaitWorkShift(
					(String) entity.getProperty("name"),
					(Date) entity.getProperty("from"),
					(Date) entity.getProperty("to"),
					(Long) entity.getProperty("hours"));
			waitWorkShift.setId(KeyFactory.keyToString(entity.getKey()));
		}
		return waitWorkShift;
	}

}
